// 格式化价格
export const formatPrice = (price: number | string, unit?: string): string => {
  const numPrice = typeof price === 'string' ? parseFloat(price) : price;
  if (isNaN(numPrice)) return '价格面议';
  
  return `¥${numPrice.toLocaleString('zh-CN')}${unit ? `/${unit}` : ''}`;
};

// 格式化价格区间
export const formatPriceRange = (minPrice: number | string, maxPrice: number | string, unit?: string): string => {
  const numMin = typeof minPrice === 'string' ? parseFloat(minPrice) : minPrice;
  const numMax = typeof maxPrice === 'string' ? parseFloat(maxPrice) : maxPrice;
  
  if (isNaN(numMin) || isNaN(numMax)) return '价格面议';
  
  return `¥${numMin.toLocaleString('zh-CN')} - ¥${numMax.toLocaleString('zh-CN')}${unit ? `/${unit}` : ''}`;
};

// 格式化日期
export const formatDate = (dateString: string | Date, format: 'full' | 'short' | 'month' = 'short'): string => {
  const date = typeof dateString === 'string' ? new Date(dateString) : dateString;
  
  if (isNaN(date.getTime())) return '日期无效';
  
  switch (format) {
    case 'full':
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    case 'month':
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long'
      });
    case 'short':
    default:
      return date.toLocaleDateString('zh-CN');
  }
};

// 格式化文件大小
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 截断文本
export const truncateText = (text: string, maxLength: number): string => {
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength) + '...';
};

// 生成随机ID
export const generateId = (): string => {
  return Math.random().toString(36).substr(2, 9);
};

// 防抖函数
export const debounce = <T extends (...args: unknown[]) => unknown>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let timeout: NodeJS.Timeout;
  return (...args: Parameters<T>) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
};

// 节流函数
export const throttle = <T extends (...args: unknown[]) => unknown>(
  func: T,
  limit: number
): ((...args: Parameters<T>) => void) => {
  let inThrottle: boolean;
  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};